﻿using System;
using System.Data;
using wojilu.Apps.Qycms.Domain;
using wojilu.IO;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class TemplateController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public TemplateController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void TemplateList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            var condition = String.Empty;
            var dirlist = ctx.Get("dirlist");
            var skindir = ctx.Get("skindir");
            var filedir = ctx.Get("filedir");
            if (skindir.StrIsNullOrEmpty())
            {
                var s = Skin.find(" isclass=:i").set("i", 1).first();
                if (s == null)
                {
                    Configs c = Configs.find("valname=:v").set("v", "default_templates").first();
                    skindir = c.value;
                }
                else
                {
                    skindir = s.code;
                }
            }
            var dt = FileSystemObject.GetDirectoryInfos(strUtil.Join(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), skindir), dirlist), FsoMethod.All);
            var Count = dt.Rows.Count;
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(Count.ToString());
                ctx.web.ResponseEnd();
            }
            var builder = new MyStringBuilder();
            if (!dirlist.StrIsNullOrEmpty())
            {
                set("updirtype", 1);
                var strArray = strUtil.Split(dirlist,"/");
                var str = strArray[strArray.Length - 2] + "/";
                str = Left(dirlist, dirlist.Length - str.Length);
                var uploadurl = to(TemplateList) + "?skindir=" + skindir + "&filedir=" + filedir + "&dirlist=" + str;
                set("uploadurl", uploadurl);
            }
            else
            {
                set("updirtype", 2);
            }
            set("dirlist", dirlist);
            set("filedir", filedir);
            set("skindir", skindir);
            bind("dt", dt);
        }

        [HttpGet]
        public virtual void TemplateDel()
        {
            var dir = ctx.Get("dir");
            var filename = ctx.Get("filename");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename));
            File.Delete(filePath);
            logService.Add((User)ctx.viewer.obj, lang("templatemain_del_log") + lang("log_extra_ok"), "{file:'" + dir + filename + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void TemplateCopy()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            target(TemplateCopyDo);
            var dir = ctx.Get("dir");
            var filename = ctx.Get("filename");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename));
            var content = strUtil.EncodeTextarea(file.Read(filePath));
            content = content.Replace("#{", "&#35;{");
            set("dir", dir);
            set("filename", filename);
            set("content", content);
        }

        [HttpPost]
        public virtual void TemplateCopyDo()
        {
            var templatecode = ctx.Post("templatecode");
            var content = ctx.PostHtmlAll("content");
            var dir = ctx.Post("dir");
            var filename = ctx.Post("filename");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename));
            var newfilePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + templatecode + MvcConfig.Instance.ViewExt));
            if (file.Read(filePath.Trim()).Equals(content))
            {
                echo("没有修改内容");
                return;
            }

            file.Write(newfilePath, content);
            logService.Add((User)ctx.viewer.obj, lang("templatemain_copy_log") + lang("log_extra_ok"), "{file:'" + dir + filename + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void TemplateEdit()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            target(TemplateEditDo);
            var dir = ctx.Get("dir");
            var filename = ctx.Get("filename");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename));
            var content = strUtil.EncodeTextarea(file.Read(filePath));
            content = content.Replace("#{", "&#35;{");
            set("dir", dir);
            set("filename", filename);
            set("content", content);
        }

        [HttpPost]
        public virtual void TemplateEditDo()
        {
            var content = ctx.PostHtmlAll("content");
            var dir = ctx.Post("dir");
            var filename = ctx.Post("filename");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename));
            if (file.Read(filePath.Trim()).Equals(content))
            {
                echo("没有修改内容");
                return;
            }

            var destfilename = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + filename.Replace(".", "_" + Rand.GetFileName() + ".")));
            file.Copy(filePath, destfilename);
            file.Write(filePath, content);
            logService.Add((User)ctx.viewer.obj, lang("templatemain_copy_log") + lang("log_extra_ok"), "{file:'" + dir + filename + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void CheckCode()
        {
            var dir = ctx.Get("dir");
            var filename = ctx.Get("filename");
            var templatecode = ctx.Post("templatecode");
            var filePath = PathHelper.Map(strUtil.Join(strUtil.Join(MvcConfig.Instance.ViewDir, "templates"), dir + "/" + templatecode + MvcConfig.Instance.ViewExt));
            if (file.Exists(filePath))
            {
                ctx.web.ResponseWrite("false");
            }
            else
            {
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void TemplateMain()
        {
            var inputtext = ctx.Get("inputtext");
            var typeclass = ctx.Get("typeclass");
            var skindir = ctx.Get("skindir");
            var filedir = ctx.Get("filedir");
            var fileclass = ctx.Get("fileclass");
            var digheight = ctx.GetInt("digheight");
            var IframeName = ctx.Get("IframeName");
            var LoadUrl = "&inputtext=" + inputtext + "&typeclass=" + typeclass + "&skindir=" + skindir + "&filedir=" + filedir + "/&fileclass=" + fileclass + "&digheight=" + digheight + "&iframename=" + IframeName;
            set("fheight", digheight);
            set("loadurl", LoadUrl);
            set("iframename", IframeName);
            set("inputtext", inputtext);
            var dirlist = String.Empty;
            var templateDIR = "templates";
            if (!skindir.StrIsNullOrEmpty())
            {
                dirlist = MvcConfig.Instance.ViewDir + templateDIR + "/" + skindir + "/" + DefaultLng + "/" + filedir;
                if (skindir != "wap")
                {
                    set("updirtype", 1);
                }
                else
                {
                    set("updirtype", 2);
                }
                var s = Left(dirlist, dirlist.LastIndexOf("/"));
                set("dirlist1", s);
            }
            else
            {
                var s = Skin.find(" isclass=:i").set("i", 1).first();
                if (s == null)
                {
                    Configs c = Configs.find("valname=:v").set("v", "default_templates").first();
                    skindir = c.value;
                }
                else
                {
                    skindir = s.code;
                }
                dirlist = MvcConfig.Instance.ViewDir + templateDIR + "/" + skindir + "/" + DefaultLng + "/" + filedir;
                set("updirtype", 2);
            }
            dirlist += "/";
            var filelist = FileSystemObject.GetDirectoryInfos(dirlist, FsoMethod.All);
            bind("filelist", filelist);
            set("templateDIR", templateDIR);
            set("dirlist", dirlist);
            var uploadurl = String.Empty;
            if (filedir.IndexOf("/") != -1)
            {
                uploadurl = to(TemplateMain) + "?action=listwindow&inputtext=" + inputtext + "&typeclass=" + typeclass + "&skindir=" + skindir + "&fileclass=" + fileclass + "&digheight=" + digheight + "&filedir=" + Left(filedir, filedir.LastIndexOf("/"));
            }
            else
            {
                uploadurl = to(TemplateMain) + "?action=listwindow&inputtext=" + inputtext + "&typeclass=" + typeclass + "&skindir=" + skindir + "&fileclass=" + fileclass + "&digheight=" + digheight + "&filedir=" + filedir + "/";
            }
            set("uploadurl", uploadurl);

        }

        [HttpGet]
        public virtual void MailTemplateMain()
        {
            var inputtext = ctx.Get("inputtext");
            var typeclass = ctx.Get("typeclass");
            var styleclass = ctx.Get("styleclass");
            var digheight = ctx.Get("digheight");
            var IframeName = ctx.Get("IframeName");
            set("fheight", digheight);
            set("loadurl", "");
            set("iframename", IframeName);
            set("inputtext", inputtext);
            var templateslist = wojilu.Apps.Qycms.Domain.Templates.find(" styleclass=" + styleclass + " and lng='" + DefaultLng + "'").list();
            bind("templateslist", templateslist);
        }

    }
}
